// src/hooks/useEventBus.ts
import { onUnmounted } from "vue";

type EventHandler<T = any> = (payload?: T) => void;
type EventBusKey = string | symbol;

interface EventBus {
  on(key: EventBusKey, handler: EventHandler): void;
  off(key: EventBusKey, handler?: EventHandler): void;
  emit<T = any>(key: EventBusKey, payload?: T): void;
  once(key: EventBusKey, handler: EventHandler): void;
}

export function useEventBus(): EventBus {
  const events = new Map<EventBusKey, Set<EventHandler>>();

  const eventBus: EventBus = {
    on(key, handler) {
      if (!events.has(key)) {
        events.set(key, new Set());
      }
      events.get(key)?.add(handler);
    },

    off(key, handler) {
      if (!handler) {
        events.delete(key);
        return;
      }
      events.get(key)?.delete(handler);
    },

    emit(key, payload) {
      events.get(key)?.forEach((handler) => handler(payload));
    },

    once(key, handler) {
      const onceHandler = (payload?: any) => {
        handler(payload);
        eventBus.off(key, onceHandler);
      };
      eventBus.on(key, onceHandler);
    },
  };

  // 自动注销组件内注册的事件
  const autoUnsubEvents = new Set<{
    key: EventBusKey;
    handler: EventHandler;
  }>();
  const autoUnsubOn = (key: EventBusKey, handler: EventHandler) => {
    eventBus.on(key, handler);
    autoUnsubEvents.add({ key, handler });
  };

  onUnmounted(() => {
    autoUnsubEvents.forEach(({ key, handler }) => {
      eventBus.off(key, handler);
    });
    autoUnsubEvents.clear();
  });

  return {
    ...eventBus,
    on: autoUnsubOn, // 替换原来的on方法，增加自动注销功能
  };
}
